package org.smoke.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

/**
 * for encrypt and decryption
 * @author hezhiyu on 14-9-23.
 */
public class CipherUtil {

    /** doc: http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html
     *       http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Cipher
     * */

    private static final int AES_KEY_SIZE     = 16;
    private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";

    public static String encByAES(String str2Encrypt, String key) throws Exception {
        SecretKeySpec secretKeySpec = buildAESCipherKey(key.getBytes());
        byte[] data = dealWithAES(str2Encrypt.getBytes(), secretKeySpec, Cipher.ENCRYPT_MODE);
        return Base64.encodeBase64String(data);
    }

    public static String encByAES(String str2Encrypt, SecretKeySpec secretKeySpec) throws Exception{
        byte[] data = dealWithAES(str2Encrypt.getBytes(), secretKeySpec, Cipher.ENCRYPT_MODE);
        return new String(data);
    }

    public static String decByAES(String str2Decrypt, String key) throws Exception {
        SecretKeySpec secretKeySpec = buildAESCipherKey(key.getBytes());
        byte[] data = dealWithAES(Base64.decodeBase64(str2Decrypt), secretKeySpec, Cipher.DECRYPT_MODE);
        return new String(data);
    }

    public static String decByAES(String str2Decrypt, SecretKeySpec secretKeySpec) throws Exception {
        byte[] data = dealWithAES(str2Decrypt.getBytes(), secretKeySpec, Cipher.DECRYPT_MODE);
        return new String(data);
    }

    private static byte[] dealWithAES(byte[] data, SecretKeySpec secretKeySpec, int mode) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(mode ,secretKeySpec);
        return cipher.doFinal(data);
    }

    private static SecretKeySpec buildAESCipherKey(byte[] key) throws Exception {
        key = Arrays.copyOfRange(key, 0, AES_KEY_SIZE);
        return new SecretKeySpec(key, "AES");
    }
}
